combinatorics constructive algorithms greedy math *1900

Please click on ads to support us..

Python Code:

def solve():
    mod = 1000000007
    n, k = map(int, input().strip().split())

    res = pow(2, n, mod)

    if k >= n:
        print(res)
    elif k + 1 == n:
        print(res - 1)
    else:
        ans = 1
        temp1 = 1
        temp2 = 1
        for i in range(1, n - k):
            temp1 *= (n - i + 1)
            temp1 %= mod
            temp2 *= i
            temp2 %= mod
            ans += temp1 * pow(temp2, mod - 2, mod) % mod
        print((res - ans + mod) % mod)


if __name__ == '__main__':
    solve()

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define F first
#define S second
#define pb push_back
#define B break
#define C continue
#define mid ((l+r)/2)
#define left (2*idx)
#define right (2*idx+1)

using namespace std;

const ll Mod=1e9+7 , N = 500500 , inf=1e18;
ll n , m , k , q , x , y , z , a[N], fact[N], inv[N] , ans=0 , sum=0 , mn=inf , mx=0 ;

ll poww(ll a,ll b,ll Mod){
    ll res=1;if(b<0)b=(b%(Mod-1)+Mod-1)%(Mod-1);
    for(;b;b>>=1,a=1ll*a*a%Mod)
        if(b&1)res=1ll*res*a%Mod;
    return res;
}

ll Cnk(ll n,ll k){
    if(k>n)return 0;
    return (((fact[n]*inv[k])%Mod) * inv[n-k])%Mod;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    fact[0]=1;
    for(ll i=1 ; i<N ; i++)     fact[i] = (fact[i-1]*i)%Mod;

    inv[N-1] = poww(fact[N-1],-1,Mod);
    for(ll i=N-2 ; i>=0 ; i--)  inv[i] = (inv[i+1]*(i+1))%Mod;

    int t=1;
    //cin >> t ;
    while(t--){
        bool ok=1;
        cin >> n >> k ;
        ans=0;
        for(int i=0 ; i<=k && i<=n ; i++){
            ans += Cnk(n,i);
            ans %= Mod;
        }
        cout << ans << endl;
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1593C - Save More Mice
1217. Minimum Cost to Move Chips to The Same Position
347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference
1619B - Squares and Cubes